Page({
  data: {
    dailyVote:0,//每日一投
    dailyVoteType:["仅限一次","每天一次"],
    descImgUrls:["../../imgs/addDescImg.png"],//描述图片
    imgUrl:'../../imgs/addImg.png',//自定义分享图
    displayOption:0,//是否显示票数
    displayOptionType:["显示票数","不显示票数"],
    shuffleOptions:false,//是否打乱顺序
    needPersonalInformation:false,//是否需要个人信息
    isPictureVote:false,//是否为图文投票
    multiple: false, //单选多选
    allowGroupVote:0,//只允许群成员投票
    formTitle: '',
    formDesc: '',
    optionList: [],
    optionImgList: [],//选项图
    nowDate: '',
    nowTime: '',
    endDate: '',
    isAnonymous: false,
    buttonDisable:false,

    minOptionNum: '2',
    maxOptionNum:' ',  
  },
  onLoad(options) {
    this.formReset()
  },
  onTitleInputChange(e) {
    this.setData({
      formTitle: e.detail.value
    })
  },
  onDescChange(e) {
    this.setData({
      formDesc: e.detail.value
    })
  },
  onTapUploadImg(e) {
    console.log(e)
    let index = e.currentTarget.dataset.optionIndex
    let that = this
    wx.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success (res) {
          // tempFilePath可以作为img标签的src属性显示图片
          const tempFilePaths = res.tempFilePaths
          wx.uploadFile({
            //url: 'https://www.intohash.com/vote_backend/main/uploadImg', //仅为示例，非真实的接口地址
            url: 'http://localhost:8010/vote_backend/main/uploadImg',
            filePath: tempFilePaths[0],
            name: 'file',
            success (res){
              const data = res.data
              let imgurl = JSON.parse(data).data
              let imgList = that.data.optionImgList
              imgList[index] = imgurl
              that.setData({
                  optionImgList:imgList
              })
              console.log(imgList)
            }
          })
          /*let imgList = that.data.optionImgList
          imgList[index] = tempFilePaths
          that.setData({
            optionImgList:imgList
          })*/
        }
      })
},
onTapUploadDescImg(e) {
  console.log(e)
  let that = this
  wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success (res) {
        // tempFilePath可以作为img标签的src属性显示图片
        const tempFilePaths = res.tempFilePaths
        wx.uploadFile({
          //url: 'https://www.intohash.com/vote_backend/main/uploadImg', //仅为示例，非真实的接口地址
          url: 'http://localhost:8010/vote_backend/main/uploadImg',
          filePath: tempFilePaths[0],
          name: 'file',
          success (res){
            const data = res.data
            let imgurl = JSON.parse(data).data
            let descImgList=[]
            descImgList.push(imgurl)
            that.setData({
              descImgUrls:descImgList
            })
          }
        })
        // let imgList = that.data.descImgUrls
        // imgList = tempFilePaths
        // that.setData({
        //   descImgUrls:imgList
        // })
      }
    })
},
onTapUploadShareImg(e) {
  console.log(e)
  //let index = e.currentTarget.dataset.optionIndex
  let that = this
  wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success (res) {
        // tempFilePath可以作为img标签的src属性显示图片
        const tempFilePaths = res.tempFilePaths
        wx.uploadFile({
          //url: 'https://www.intohash.com/vote_backend/main/uploadImg', //仅为示例，非真实的接口地址
          url: 'http://localhost:8010/vote_backend/main/uploadImg',
          filePath: tempFilePaths[0],
          name: 'file',
          success (res){
            const data = res.data
            let imgurl = JSON.parse(data).data
            that.setData({
              imgUrl:imgurl
            })
            console.log(imgurl)
          }
        })
        /*let imgList = that.data.imgUrl
        imgList = tempFilePaths
        that.setData({
          imgUrl:imgList
        })*/
      }
    })
},
  onTapAddOption() {
    const newOptionList = this.data.optionList
    const newOptionImgList = this.data.optionImgList
    newOptionList.push('')
    newOptionImgList.push('../../imgs/addImg.png')

  const newMaxOptionNum = newOptionList.length;

    this.setData({
      optionList: newOptionList,
      optionImgList: newOptionImgList,
      maxOptionNum: newMaxOptionNum,
    })
  },
  onOptionInputChange(e) {
    const newOptionList = this.data.optionList
    const changedIndex = e.currentTarget.dataset.optionIndex
    newOptionList[changedIndex] = e.detail.value
    this.setData({
      optionList: newOptionList
    })
  },
  onTapDelOption(e) {
    const delIndex = e.currentTarget.dataset.optionIndex
    const newOptionList = this.data.optionList.filter(
      (v, i) => i !== delIndex
    )
    const newOptionImgList = this.data.optionImgList.filter(
      (v,i) => i != delIndex
    )
    this.setData({
      optionList: newOptionList,
      optionImgList: newOptionImgList
    })
  },
  onChangeisPictureVote(e) {
    this.setData({
      isPictureVote: e.detail.value
    })
  },
  onChangedailyVote(e) {
    this.setData({
      dailyVote: e.detail.value
    })
  },
  onChangedisplayOption(e) {
    this.setData({
      displayOption: e.detail.value
    })
  },
  onChangeshuffleOptions(e) {
    this.setData({
      shuffleOptions: e.detail.value
    })
  },
  onChangeneedPersonalInformation(e) {
    this.setData({
      needPersonalInformation: e.detail.value
    })
  },
  onChangenowTime(e) {
    const nowTime = e.detail.value;
    const nowDate = this.data.nowDate;
    const endDate = nowDate + ' ' + nowTime;
    this.setData({
      nowTime:nowTime,
      endDate: endDate
    })
  },
  onChangenowDate(e) {
    const nowDate = e.detail.value;
    const nowTime = this.data.nowTime;
    const endDate = nowDate + ' ' + nowTime;
    this.setData({
      nowDate:nowDate,
      endDate: endDate
    })
  },
  onChangemultiple(e) {
    console.log(e.detail.value);
    this.setData({
      multiple: e.detail.value
    })
  },

  setMinOptionNumLimit(e){
    this.setData({
        minOptionNum: e.detail.value
     });
     console.log(this.data.minOptionNum);
},  

setMaxOptionNumLimit(e){
  this.setData({
      maxOptionNum: e.detail.value
   });
   console.log(this.data.maxOptionNum);
},   

  onChangeIsAnonymous(e) {
    this.setData({
      isAnonymous: e.detail.value
    })
  },
  onChangeallowGroupVote(e) {
    this.setData({
      allowGroupVote: e.detail.value
    })
  },
  // 校验表单数据是否完整，如果校验通过就返回null，否则返回需要提示的文字
  checkFormValid() {
    if (!this.data.formTitle) {
      return '标题不能为空'
    }
    if (this.data.optionList.length < 2) {
      return '至少需要2个选项'
    }
    for (let i = 0; i < this.data.optionList.length; i++) {
      if (!this.data.optionList[i]) {
        return '选项不能为空'
      }
    }
    return null
  },


  // 时间校验函数
  checkExpired(endDate) {
    const now = new Date();
    const endDateArray = endDate[0].split('-') // 将字符串分割成字符数组，分隔符为-
    const endYear = Number(endDateArray[0]) // 取字符数组中的年份，并将数据类型转换为number
    const endMonth = Number(endDateArray[1]) // 取字符数组中的月份，并将数据类型转换为number
    const endDay = Number(endDateArray[2]) // 取字符数组中的日期，并将数据类型转换为number

    const endDateArray2 = endDate[1].split(':') 
    const endHour = Number(endDateArray2[0]) 
    const endMinute = Number(endDateArray2[1]) 

    const time = new Date(endYear,endMonth-1,endDay,endHour,endMinute);
    console.log('now',now)
    console.log('time',time)
    if(now > time){
      console.log('投票时间已截止');
      return true;
    }else{
      console.log('投票时间未截止');
      return false;
    }
  },

 

  formSubmit() {
    // 提交前需要先对表单内容进行校验
    const msg = this.checkFormValid()
    if (msg) {        // 在if判断时，null会被转换为false
      wx.showToast({  // 调用提示框API显示提示内容
        title: msg,   // 提示框中的文字内容
        icon: 'none'  // 提示框的图标，none表示没有图标
      })
      return           // 提前返回，函数会在这里结束，后面的内容不会执行
    }

    let minOptionNum = this.data.minOptionNum;
    let maxOptionNum = this.data.maxOptionNum;
    let optionList = this.data.optionImgList;
    let endDateAndTimeArray = this.data.endDate.split(' ');
    let that = this
    wx.showModal({
      title: '温馨提示',
      content: '投票创建后不支持再次修改，请确认',
      success (res) {
        if (res.confirm) {
          console.log('用户点击确定')
          if(minOptionNum >= 1 && minOptionNum <= optionList.length && maxOptionNum >= 1 && maxOptionNum <= optionList.length && minOptionNum <= maxOptionNum){ // 选项数限制正确
            if(that.checkExpired(endDateAndTimeArray) == false){ // 选项数限制正确，投票时间未截止
            wx.showLoading({
              title: '加载中',
              mask:true
            })
            that.setData({
              buttonDisable:!that.data.buttonDisable
            })
            // 校验通过时后面的内容才会被执行
            const formData = {  // 将表单的数据放到一个formData对象中
              "endDate": that.data.endDate,
              "isAnonymous": that.data.isAnonymous?1:0,
              "dailyVote": that.data.dailyVote,
              "displayOption": that.data.displayOption,
              "shuffleOptions": that.data.shuffleOptions?1:0,
              "needPersonalInformation": that.data.needPersonalInformation?1:0,
              "optionList": that.data.optionList,
              "title": that.data.formTitle,
              "type": that.data.multiple?1:0,
              "voteType": that.data.isPictureVote?1:0,
              "urls": that.data.optionImgList,
              "descImgUrls": that.data.descImgUrls,
              "imgUrl": that.data.imgUrl,
              "userId": wx.getStorageSync('userid'),
              "voteDesc": that.data.formDesc,  
              "onlyGroupMember": that.data.allowGroupVote?1:0,
            }
            console.log(formData)
            wx.request({
              //url: "https://www.intohash.com/vote_backend/user/addVote",
              url: "http://localhost:8010/vote_backend/user/addVote",
              method:"POST",
              data:{
                  "endDate": that.data.endDate,
                  "isAnonymous": that.data.isAnonymous?1:0,
                  "dailyVote": that.data.dailyVote,
                  "displayOption": that.data.displayOption,
                  "shuffleOptions": that.data.shuffleOptions?1:0,
                  "needPersonalInformation": that.data.needPersonalInformation?1:0,
                  "optionList": that.data.optionList,
                  "title": that.data.formTitle,
                  "type": that.data.multiple?1:0,
                  "voteType": that.data.isPictureVote?1:0,
                  "urls": that.data.optionImgList,
                  "descImgUrls": that.data.descImgUrls,
                  "imgUrl": that.data.imgUrl,
                  "userId": wx.getStorageSync('userid'),
                  "voteDesc": that.data.formDesc,  
                  "onlyGroupMember": that.data.allowGroupVote?1:0,
                  "leastLimit":that.data.minOptionNum,
                  "mostLimit":that.data.maxOptionNum
              },
              success: function (e) {
                //返回userid 用户评论
                  wx.hideLoading()
                console.log('创建投票成功')
                console.log(e)
                let voteid = e.data.data.voteId
                
                wx.redirectTo({       // 自动跳转到参与投票页面
                  url: '/pages/vote/vote?voteID=' + voteid + '&CreatedOrJoined=0',//0代表从我创建的页面进入
                })
              }
              , fail: function (e) {
                wx.hideLoading()
                that.setData({
                  buttonDisable:!that.data.buttonDisable
                })
                wx.showToast({            // 创建投票失败时，显示提示框提示用户
                  title: '创建投票失败',  // 提示框中的文字内容
                  icon: 'none'            // 提示框的图标，none表示没有图标
                })
              }
            });

          }
          else{
            wx.showModal({ // 选项数限制正确，投票时间已截止
              title:'提示',
              content: '请设置正确的投票截止日期',
              confirmText:'我知道了',
              showCancel:false
            })

          }
        }
        else{ //选项数限制错误
          if(this.checkExpired(endDateAndTimeArray) == false){ // 选项数限制错误，投票时间未截止
            wx.showModal({
              title:'提示',
              content: '请设置正确的可选选项数限制',
              confirmText:'我知道了',
              showCancel:false
            })
          }
          else{// 选项数限制错误，投票时间已截止
            wx.showModal({
              title:'提示',
              content: '请设置正确的可选选项数限制和正确的投票截止日期',
              confirmText:'我知道了',
              showCancel:false
            })
          }
        }
        } else if (res.cancel) {
          console.log('用户点击取消') 
        }
      }
    })
  },
  formReset() {
    const now = new Date()
    const nowYear = now.getFullYear()
    const nowMonth = now.getMonth()+1
    const nowDay = now.getDate()
    const nowHour = now.getHours();
    const nowMinute = now.getMinutes();
    const nowDate = nowYear +
      '-' +
      ((nowMonth < 10) ? ('0' + nowMonth) : nowMonth) +
      '-' +
      ((nowDay < 10) ? ('0' + nowDay) : nowDay);

    const nowTime = ((nowHour < 10)?('0' + nowHour) : nowHour) +
      ':' +
      ((nowMinute < 10)?('0' + nowMinute) : nowMinute) ;
    this.setData({
      nowDate,
      nowTime,
      endDate: nowDate+ ' ' + nowTime,
      formTitle: '',
      formDesc: '',
      optionList: [],
      isAnonymous: false,
      dailyVote: 0,
      displayOption: 0,
      shuffleOptions: false,
      needPersonalInformation: false,
      allowGroupVote:0
    })
  }
})
